<template>
  <view>
    <!-- 上面的进度条 -->
    <view class="od-banner">
      <image
        class="od-banner-icon"
        src="/static/resource/images/od_bg_icon.png"
        mode="widthFix"
      />
      <view class="od-jd od-jd-0">
        <view class="od-jd-out">
          <view class="od-jd-in"></view>
        </view>
        <view class="vp-flex od-jd-text">
          <view class="vp-flex_1">
            <text class="od-jd-st-0">填写订单</text>
          </view>
          <view class="vp-flex_1">
            <text class="od-jd-st-10">在线支付</text>
          </view>
          <view class="vp-flex_1">
            <text class="od-jd-st-20">专人服务</text>
          </view>
          <view class="vp-flex_1">
            <text class="od-jd-st-30">服务完成</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 中间的医院+服务内容 -->
    <view class="pub-box">
      <view class="pub-box-bd">
        <view class="weui-cell weui-cell_input">
          <view class="weui-cell__hd">
            <image
              class="serv-icon"
              :src="
                service.icon_image
                  ? service.icon_image_url
                  : '../../static/resource/images/avatar.jpg'
              "
            >
            </image>
          </view>
          <view class="weui-cell__bd">
            <text class="serv-name">{{ service.name }}</text>
          </view>
          <view class="weui-cell__ft">
            <view class="f5 ic_info" @click="handleTap">服务内容</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 尊享陪诊  index页面中中间的5个navs-->
    <block
      v-if="service.stype == 10 || service.stype == 15 || service.stype == 20"
    >
      <view class="pub-box">
        <view class="pub-box-bd">
          <!-- 就诊医院 -->
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">
              <view class="weui-label">就诊医院</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <view>
                <picker
                  @change="onHospitalChange"
                  :value="hospitalIndex"
                  :range="hospitals"
                  range-key="name"
                >
                  <input
                    type="text"
                    :disabled="true"
                    placeholder="请选择要就诊的医院"
                    :value="hospitals[hospitalIndex].name"
                    placeholder-class="vp-placeholder"
                  />
                </picker>
              </view>
            </view>
          </view>
          <!-- 就诊时间 -->
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">
              <view class="weui-label">就诊时间</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <view>
                <dtPicker
                  @dtPickerChanged="onStartTimeChanged"
                  :timestamp="order.starttime"
                  placeholder="请选择就诊时间"
                >
                </dtPicker>
              </view>
            </view>
          </view>
          <!-- 就诊人信息 -->
          <view class="weui-cell weui-cell_input" @click="onClientChange">
            <view class="weui-cell__hd">
              <view class="weui-label">就诊人</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <view>
                <input
                  class="weui-input"
                  placeholder-class="vp-placeholder"
                  placeholder="请选择就诊人"
                  style="text-align: right"
                  :disabled="true"
                  :value="client.name"
                  type="text"
                />
              </view>
            </view>
          </view>
          <!-- 接送地址 -->
          <block v-if="service.stype == 15">
            <!-- 接送陪诊 -->
            <view class="weui-cell weui-cell_input">
              <view class="weui-cell__hd">接送地址</view>
              <view class="weui-cell__bd">
                <input
                  class="weui-input"
                  name="receiveAddress"
                  style="text-align: right"
                  placeholder-class="vp-placeholder"
                  placeholder="请填写就诊人所在地址"
                  v-model="order.receiveAddress"
                />
              </view>
            </view>
          </block>
          <!-- 联系电话 -->
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">联系电话</view>
            <view class="weui-cell__bd">
              <input
                class="weui-input"
                type="number"
                name="tel"
                style="text-align: right"
                placeholder-class="vp-placeholder"
                placeholder="请填写您的联系电话"
                v-model="order.tel"
              />
            </view>
          </view>
        </view>
      </view>
      <!-- 服务需求 -->
      <view class="pub-box">
        <view class="pub-box-tt">服务需求</view>
        <view class="pub-box-bd">
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__bd">
              <textarea
                name="demand"
                auto-height
                placeholder="请简单描述您要就诊的科室.."
                placeholder-class="vp-placeholder"
                style="min-height: 150rpx"
                v-model="order.demand"
              />
            </view>
          </view>
        </view>
      </view>
    </block>
    <!-- 代跑取药  index页面中中间的5个navs-->
    <block v-if="service.stype == 30 || service.stype == 40">
      <view class="pub-box">
        <view class="pub-box-bd">
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">
              <view class="weui-label">所在医院</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <view>
                <picker
                  @change="onHospitalChange"
                  :value="index"
                  :range="hospitals"
                  range-key="name"
                >
                  <input
                    type="text"
                    :disabled="true"
                    placeholder="请选择就诊所在医院"
                    :value="hospitals[hospitalIndex].name"
                    placeholder-class="vp-placeholder"
                  />
                </picker>
              </view>
            </view>
          </view>

          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">
              <view class="weui-label">服务时间</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <view>
                <dtPicker
                  @dtPickerChanged="onStartTimeChanged"
                  :timestamp="order.starttime"
                  placeholder="请选择期望服务时间"
                >
                </dtPicker>
              </view>
            </view>
          </view>
          <!-- 收件信息 -->
          <view class="weui-cell weui-cell_input" @click="onAddressChange">
            <view class="weui-cell__hd">
              <view class="weui-label">收件信息</view>
            </view>
            <view class="weui-cell__bd"></view>
            <view class="weui-cell__ft weui-cell__ft_in-access">
              <input
                class="weui-input"
                :disabled="true"
                style="text-align: right"
                placeholder-class="vp-placeholder"
                placeholder="请选择收件信息"
                :value="
                  order.address.userName
                    ? order.address.userName +
                      '(' +
                      order.address.cityName +
                      order.address.countyName +
                      order.address.detailInfo +
                      ')'
                    : ''
                "
              />
              <!-- {{order.address?(order.address.userName+'('+order.address.telNumber+')'):''}} -->
            </view>
          </view>
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__hd">联系电话</view>
            <view class="weui-cell__bd">
              <input
                class="weui-input"
                type="number"
                name="tel"
                style="text-align: right"
                placeholder-class="vp-placeholder"
                placeholder="请填写您的联系电话"
                v-model="order.tel"
              />
            </view>
          </view>
        </view>
      </view>

      <view class="pub-box">
        <view class="pub-box-tt">服务需求</view>
        <view class="pub-box-bd">
          <view class="weui-cell weui-cell_input">
            <view class="weui-cell__bd">
              <textarea
                name="demand"
                auto-height
                placeholder="如有其他服务要求请在此填写.."
                placeholder-class="vp-placeholder"
                style="min-height: 150rpx"
                v-model="order.demand"
              />
            </view>
          </view>
        </view>
      </view>
    </block>
    <!-- 中间空白区域 -->
    <view style="height: 300rpx"></view>
    <!-- 悬浮提交按钮 -->
    <view class="vp-foot">
      <view style="background: #ffffff; padding: 20rpx">
        <view class="xieyi" style="text-align: center">
          <text
            :class="'is_xieyi ' + (is_xieyi ? 'is_xieyi_on' : '')"
            @click="onXieyiChange"
            >我已阅读并同意</text
          >
          <navigator :url="cfg.page_xy">《用户协议》</navigator>
          <text>和</text>
          <navigator :url="cfg.page_fw">《服务协议》</navigator>
        </view>
        <view>
          <button
            :class="'btnp ' + (is_xieyi ? '' : 'btnp-disabled')"
            @click="submit"
          >
            确认下单
            <block v-if="order.price > 0">（支付{{ order.price }}元）</block>
          </button>
        </view>
      </view>
    </view>
    <!-- 提交订单输入手机号 -->
    <uni-popup
      ref="popup"
      type="center"
      :is-mask-click="false"
      background-color="#fff"
    >
      <view class="popup-content">
        <view class="group">
          <input
            class="uni-input"
            type="tel"
            v-model="validMobile.phone"
            placeholder="手机号"
          />
        </view>
        <view class="group">
          <input
            class="uni-input"
            v-model="validMobile.validCode"
            placeholder="验证码"
          />
          <text class="valid-text" @click="countdownChange">{{
            countdown.validText
          }}</text>
        </view>
      </view>
      <view class="btns">
        <view class="cancal" @click="cancal">取消</view>
        <view class="ok" @click="ok">确定</view>
      </view>
    </uni-popup>
    <!-- 支付二维码弹窗户 -->
    <uni-popup
      ref="uqrCode"
      type="center"
      :is-mask-click="false"
      background-color="#fff"
    >
      <view class="pay-box">
        <image
          @click="payment"
          src="../../static/resource/images/modal_closer.png"
          style="display: block; width: 30rpx; height: 30rpx"
        ></image>
        <view class="text-center">微信支付</view>
        <canvas
          id="qrcode"
          canvas-id="qrcode"
          style="width: 300rpx; height: 300rpx"
        ></canvas>
        <view class="text-center">请用本人微信扫描以上二维码</view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import UQRCode from 'uqrcodejs' // 生成二维码
import dtPicker from '../../compontents/dtPicker/dtPicker'
import { onLoad } from '@dcloudio/uni-app'
import { ref, toRaw, reactive } from 'vue'
const app = getApp()

// 页面服务详情数据
const service = ref({
  name: ''
})
// 医院数据
const hospitals = ref([])
// 订单数据  最后用于提交订单
const order = ref({
  price: '',
  starttime: '',
  address: {
    userName: '',
    cityName: '',
    countyName: '',
    detailInfo: ''
  },
  demand: ''
})
// 用户协议和服务协议
const cfg = ref({
  page_xy: '',
  page_fw: ''
})
// 是否勾选用户协议
const is_xieyi = ref(false)
// 设置医院选中的index
const hospitalIndex = ref(0)
const client = reactive({
  name: ''
})

onLoad(options => {
  // console.log('option', options)
  getService(options)
})
// 获取服务数据
const getService = options => {
  app.globalData.utils.request({
    url: '/Service/order',
    data: {
      svid: options.svid
    },
    success: res => {
      console.log('获取服务数据', res)
      service.value = res.data.data.service
      hospitals.value = res.data.data.hospitals
      // 设置默认选中的医院
      if (options.hid > 0) {
        hospitals.value.forEach(item => {
          if (item.id == options.hid) {
            console.log('id', hospitals.value.indexOf(item))
            hospitalIndex.value = hospitals.value.indexOf(item)
            order.value.price = item.service_price
          }
        })
      }
    }
  })
}
// 点击弹出服务提醒
const handleTap = () => {
  console.log('点击弹出服务提醒')
}
// 更改医院
const onHospitalChange = e => {
  // e.detail 就是选中的值  之前绑定的就是 index
  const value = parseInt(e.detail.value)
  hospitalIndex.value = value
  order.value.price = hospitals.value[value].service_price
}
// 修改就诊时间
const onStartTimeChanged = e => {
  console.log('修改就诊时间', e)
  order.value.starttime = e.detail.value
}
// 更改就诊人
const onClientChange = () => {
  uni.navigateTo({
    // 添加参数  后续判断来自什么页面
    url: '/pages/clients/index?act=select'
  })
}
// 监听全局事件
uni.$on('clientChange', data => {
  console.log('监听全局事件-修改就诊人', data)
  client.name = data.name
  client.age = data.age
  client.mobile = data.mobile
  client.sex = data.sex
})
// 勾选同意服务按钮
const onXieyiChange = () => {
  is_xieyi.value = !is_xieyi.value
}
// 收件信息
const onAddressChange = () => {
  uni.chooseAddress({
    success: res => {
      // console.log('uni.chooseAddress成功', res)
      order.value.address.userName = res.userName
      order.value.address.cityName = res.cityName
      order.value.address.countyName = res.countyName
      order.value.address.detailInfo = res.detailInfo
    },
    fail: res => {
      console.log('uni.chooseAddress失败', res)
    }
  })
}
// 手机号  验证码
const validMobile = ref({
  phone: '',
  validCode: ''
})
// 验证码 倒计时
const countdown = ref({
  validText: '获取验证码',
  time: 60
})
// 点击取消
const cancal = () => {
  console.log('点击取消')
}
// 定义一个验证码是否可以点击的状态 默认不可以点击
let flag = false
// 点击发送验证码
const countdownChange = () => {
  console.log('点击发送验证码')
  if (!validMobile.value.phone) {
    return uni.showToast({
      title: '请填写手机号码!',
      icon: 'none',
      duration: 1000
    })
  }
  if (flag) return
  const time = setInterval(() => {
    if (countdown.value.time <= 0) {
      countdown.value.validText = '获取验证码'
      countdown.value.time = 60
      clearInterval(time)
      flag = false
    } else {
      countdown.value.time -= 1
      countdown.value.validText = `剩余${countdown.value.time}s`
    }
  }, 1000)
  flag = true
  app.globalData.utils.request({
    url: '/get/code',
    method: 'POST',
    data: {
      tel: validMobile.value.phone
    },
    success: res => {
      console.log('获取验证码', res)
    },
    fail: res => {
      uni.showToast({
        title: res.data.msg,
        icon: 'none',
        duration: 1000
      })
    }
  })
}

// 点击确认
const ok = () => {
  // 判断手机号 验证码是否为空
  if (validMobile.value.phone === '') {
    return uni.showToast({
      title: '手机号不能为空',
      icon: 'none',
      duration: 1000
    })
  }
  if (validMobile.value.validCode === '') {
    return uni.showToast({
      title: '请填写验证码',
      icon: 'none',
      duration: 1000
    })
  }
  // 点击确定  验证码检验
  app.globalData.utils.request({
    url: '/user/authentication',
    method: 'POST',
    data: {
      tel: validMobile.value.phone,
      code: validMobile.value.validCode
    },
    success: res => {
      uni.setStorageSync('token', res.data.data.token)
      // 创建订单
      console.log('创建订单', order.value)
      // createOrder(order.value)
    },
    fail: res => {
      console.log('验证码检验失败', res)
    }
  })
}
// 用于获取 popup 组件
const popup = ref()
// 确认下单
const submit = () => {
  if (!is_xieyi.value) {
    return uni.showToast({
      title: '请先阅读并同意用户协议和服务协议!',
      icon: 'none',
      duration: 1000
    })
  }
  // 医院校验
  if (hospitalIndex.value == 0) {
    return uni.showToast({
      title: '请选择就诊医院!',
      icon: 'none',
      duration: 1000
    })
  }
  order.value.hospital_id = hospitals.value[hospitalIndex.value].id
  order.value.hospital_name = hospitals.value[hospitalIndex.value].name
  // 就诊时间
  if (order.value.starttime == '') {
    return uni.showToast({
      title: '请选择就诊时间!',
      icon: 'none',
      duration: 1000
    })
  }
  //  陪诊模块 就诊人 和 地址
  if (
    service.value.stype == 10 ||
    service.value.stype == 15 ||
    service.value.stype == 20
  ) {
    // 就诊人 这里是数组 选中iddex
    if (client.name == '') {
      return uni.showToast({
        title: '请选择就诊人!',
        icon: 'none',
        duration: 1000
      })
    }
    // 接送地址
    if (!order.value.receiveAddress) {
      return uni.showToast({
        title: '请填写接送地址!',
        icon: 'none',
        duration: 1000
      })
    }
  }
  // 添加就诊人数据
  order.value.client = {}
  order.value.client.age = client.age
  order.value.client.mobile = client.mobile
  order.value.client.name = client.name
  order.value.client.sex = client.sex
  // 带跑取药模块  收件信息
  if (service.value.stype == 30 || service.value.stype == 40) {
    if (!order.value.address.userName) {
      return uni.showToast({
        title: '请填写收件信息!',
        icon: 'none',
        duration: 1000
      })
    }
  }
  // 联系电话
  if (!order.value.tel) {
    return uni.showToast({
      title: '请填写联系电话!',
      icon: 'none',
      duration: 1000
    })
  }
  order.value.service_code = service.value.code
  order.value.service_id = service.value.id
  order.value.service_name = service.value.name
  order.value.service_stype = service.value.type
  // 最后整合需要提交的数据
  console.log('最后整合需要提交的数据', toRaw(order.value))
  // 拿不到token  证明用户没有登录
  if (!uni.getStorageSync('token')) {
    popup.value.open('center')
  } else {
    // 存在就直接下单
    // console.log('存在就直接下单', order.value)
    createOrder(order.value)
  }
}
// 支付二维码组件
const uqrCode = ref()
// 创建订单函数
const createOrder = orderData => {
  const app = getApp()
  app.globalData.utils.request({
    url: '/pay/createOrder',
    data: orderData,
    header: {
      token: uni.getStorageSync('token')
    },
    method: 'POST',
    success: res => {
      console.log('创建订单函数success', res)
      // 打开支付二维码弹窗
      uqrCode.value.open('center')
      // 获取uQRCode实例
      var qr = new UQRCode()
      // 设置二维码内容
      qr.data = res.data.wx_code
      // 设置二维码大小，必须与canvas设置的宽高一致 这里是px单位
      qr.size = 150
      // 调用制作二维码方法
      qr.make()
      // 获取canvas上下文
      var canvasContext = uni.createCanvasContext('qrcode') // 如果是组件，this必须传入
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas()
    },
    fail: res => {
      console.log('创建订单函数fail', res)
    }
  })
}
// 微信支付 跳转到订单页面
const payment = () => {
  uni.switchTab({
    url: '/pages/order/index'
  })
}
</script>

<style>
@import './index.css';
</style>
